package com.ruoyi.xdata.task;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.PageResult;
import cn.hutool.http.HttpUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.File;
import java.sql.SQLException;

/**
 * 下载文件的任务
 */
@Component("downloadTask")
public class DownloadTask {

    @Autowired
    private DataSource dataSource;

    /**
     * 下载指定SQL查询的文件
     * @param sql  select alarm_image as file from data_alarm_fire where alarm_image is not null
     * @param uri  http://192.168.1.100:8088
     * @param folder profile/
     */
    public void download(String sql, String uri, String folder) throws SQLException {
        Db db = Db.use(dataSource);
        String basePath = RuoYiConfig.getProfile()+folder;
        File baseFile = new File(basePath);
        if(!baseFile.exists() && !baseFile.isDirectory()){
            baseFile.mkdirs();
        }

        Page p = new Page(0, 100);
        while(true){
            PageResult<Entity> list = db.page(sql, p);
            if(list == null || list.isEmpty()){
                break;
            }

            for(Entity row:list){
                String filePath = row.getStr("file");
                if(StringUtils.isEmpty(filePath)){
                    continue;
                }
                String localPath = basePath+filePath;
                File localFile = new File(localPath);
                if(localFile.exists() && localFile.length() > 0){
                    continue;
                }

                try {
                    HttpUtil.downloadFile(uri + filePath, localFile);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            p.setPageNumber(p.getPageNumber()+1);
        }
    }
}
